package com.zxc.behavior.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.zxc.behavior.service.ApUnLikesBehaviorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class ApUnLikesBehaviorServiceImpl implements ApUnLikesBehaviorService {

    @Resource
    private CacheService cacheService;

    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        if (dto.getArticleId() == null || checkData(dto))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        if (dto.getType() == 0) {
            log.info("当前保存的key:{},{},{}", dto.getArticleId(), user.getId().toString(), dto);
            cacheService.hPut(BehaviorConstants.UNLIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString(), JSON.toJSONString(dto));
        } else {
            log.info("当前删除的key:{},{},{}", dto.getArticleId(), user.getId().toString(), dto);
            cacheService.hDelete(BehaviorConstants.UNLIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    private boolean checkData(UnLikesBehaviorDto dto) {
        if (dto.getType() > 1 || dto.getType() < 0) {
            return true;
        }
        return false;
    }
}
